package com.stephenone.servicedemo;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.widget.Toast;

/**
 * Created by StephenOne on 2017/7/10.
 */

public class MessengerService extends Service{
    static final int MSG_SAY_HELLO = 0;
    static final int MSG_REPLY_HELLO = 1;
    Messenger replyToClientMessenger;

    class IncommingHandler extends Handler{
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case MSG_SAY_HELLO:
                    Toast.makeText(getApplicationContext(),"服务端知道客户端sayHello",Toast.LENGTH_SHORT).show();

                    //msg.replyTo得到一个Messenger以发送消息到客户端（对客户端的消息进行相应）
                    if (msg.replyTo != null) {
                        replyToClientMessenger = msg.replyTo;
                        Message message = Message.obtain();
                        message.what = MSG_REPLY_HELLO;
                        try {
                            replyToClientMessenger.send(message);
                        } catch (RemoteException e) {
                            e.printStackTrace();
                        }
                    }
                    break;
                default:
                    super.handleMessage(msg);
            }
        }
    }

    Messenger messenger = new Messenger(new IncommingHandler());

    @Override
    public IBinder onBind(Intent intent) {
        return messenger.getBinder();
    }
}
